<script setup lang="ts">
import { ref, reactive, defineProps, defineEmits } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { uploadFoodImage } from "@/api/index";
import { useMerchantStore } from "@/store";

// 使用商家store
const merchantStore = useMerchantStore();

// 定义商品接口
interface Product {
  id?: string;
  name: string;
  price: number;
  originalPrice?: number;
  description: string;
  image: string; // 改为单个image字段，符合API文档
  inventory: number;
  categoryId: string | number;
  isFeatured: number;
  status: number;
}

// 定义分类接口
interface Category {
  id: number | string; // 分类ID可能是number或string类型
  name: string;
  icon?: string;
}

const props = defineProps({
  product: {
    type: Object as () => Partial<Product>,
    default: () => ({
      name: "",
      price: 0,
      originalPrice: 0,
      description: "",
      image: "", // 改为单张图片
      inventory: 0,
      categoryId: "",
      status: 1,
    }),
  },
  categories: {
    type: Array as () => Category[],
    default: () => [],
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["submit", "cancel"]);

const formRef = ref<FormInstance>();
const productForm = reactive<Partial<Product>>({
  name: props.product.name || "",
  price: props.product.price || 0,
  originalPrice: props.product.originalPrice || 0,
  description: props.product.description || "",
  inventory: props.product.inventory || 0,
  categoryId: props.product.categoryId || "",
  status: props.product.status !== undefined ? props.product.status : 1,
  image: props.product.image || "", // 保留原有图片URL
  isFeatured: props.product.isFeatured || 0, // 是否推荐，默认为0
});

const uploadLoading = ref(false);

// 图片上传前校验
const beforeImageUpload = (file: File) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }

  if (!isLt5M) {
    ElMessage.error("图片大小不能超过5MB！");
    return false;
  }

  return true;
};

// 处理图片上传
const handleImageUpload = async (option: any) => {
  const file = option.file;
  console.log("上传图片:", file.name);

  uploadLoading.value = true;

  try {
    const storeId = merchantStore.currentStoreId;
    if (!storeId) {
      ElMessage.error("未找到店铺ID，无法上传图片");
      uploadLoading.value = false;
      return;
    }

    // 创建FormData
    const formData = new FormData();
    formData.append("file", file);

    console.log("准备上传图片，店铺ID:", storeId);
    console.log("FormData内容:", file.name, file.size);

    // 上传图片
    const res = await uploadFoodImage(storeId, formData);
    console.log("图片上传响应:", res);

    // 处理响应
    let imageUrl = "";
    if (typeof res === "string") {
      // 如果直接返回字符串URL
      imageUrl = res;
    } else if (res.data) {
      // 如果返回对象中包含data字段
      if (typeof res.data === "string") {
        imageUrl = res.data;
      } else if (typeof res.data === "object") {
        imageUrl = res.data.data || res.data.url || res.data;
      }
    }

    if (!imageUrl) {
      throw new Error("上传失败，未获取到图片地址");
    }

    // 设置表单图片URL
    productForm.image = imageUrl;
    console.log("图片上传成功，URL:", imageUrl);

    ElMessage.success("图片上传成功");
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败，请重试");
  } finally {
    uploadLoading.value = false;
  }
};

const rules = reactive<FormRules>({
  name: [
    { required: true, message: "请输入商品名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" },
  ],
  price: [
    { required: true, message: "请输入商品价格", trigger: "blur" },
    { type: "number", min: 0, message: "价格不能小于0", trigger: "blur" },
  ],
  categoryId: [
    { required: true, message: "请选择商品分类", trigger: "change" },
  ],
  inventory: [
    { required: true, message: "请输入库存数量", trigger: "blur" },
    { type: "number", min: 0, message: "库存不能小于0", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入商品描述", trigger: "blur" },
    { min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur" },
  ],
  image: [{ required: true, message: "请上传商品图片", trigger: "change" }],
});

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  await formEl.validate(async (valid) => {
    if (valid) {
      // 检查图片是否上传
      if (!productForm.image) {
        ElMessage.warning("请上传商品图片");
        return;
      }

      console.log("提交表单，图片URL:", productForm.image);

      // 确保categoryId是数字类型
      const formData: any = { ...productForm };
      if (formData.categoryId && typeof formData.categoryId === "string") {
        formData.categoryId = parseInt(formData.categoryId);
      }

      // 确保保留商品ID (如果是编辑模式)
      if (props.product && props.product.id) {
        formData.id = props.product.id;
      }

      console.log("最终提交的表单数据:", formData);
      emit("submit", formData);
    }
  });
};

// 取消
const cancelForm = () => {
  emit("cancel");
};
</script>

<template>
  <el-form
    ref="formRef"
    :model="productForm"
    :rules="rules"
    label-width="100px"
    class="product-form"
  >
    <el-form-item label="商品名称" prop="name">
      <el-input
        v-model="productForm.name"
        placeholder="请输入商品名称"
        maxlength="50"
        show-word-limit
      />
    </el-form-item>

    <el-form-item label="商品分类" prop="categoryId">
      <el-select
        v-model="productForm.categoryId"
        placeholder="请选择商品分类"
        style="width: 100%"
      >
        <el-option
          v-for="category in categories"
          :key="category.id"
          :label="category.name"
          :value="category.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="商品价格" prop="price">
      <el-input-number
        v-model="productForm.price"
        :min="0"
        :precision="2"
        :step="0.1"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="原价" prop="originalPrice">
      <el-input-number
        v-model="productForm.originalPrice"
        :min="0"
        :precision="2"
        :step="0.1"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="库存数量" prop="inventory">
      <el-input-number
        v-model="productForm.inventory"
        :min="0"
        :precision="0"
        :step="1"
        style="width: 100%"
      />
    </el-form-item>

    <el-form-item label="商品图片" prop="image">
      <el-upload
        class="product-image-uploader"
        action=""
        :show-file-list="false"
        :before-upload="beforeImageUpload"
        :http-request="handleImageUpload"
      >
        <img
          v-if="productForm.image"
          :src="productForm.image"
          class="product-image"
        />
        <el-icon v-else class="product-image-uploader-icon"><Plus /></el-icon>
      </el-upload>
      <div class="upload-tip">支持JPG、PNG格式，大小不超过5MB</div>
    </el-form-item>

    <el-form-item label="商品描述" prop="description">
      <el-input
        v-model="productForm.description"
        type="textarea"
        :rows="4"
        placeholder="请输入商品描述"
        maxlength="500"
        show-word-limit
      />
    </el-form-item>
    <el-form-item label="是否推荐">
      <el-radio-group v-model="productForm.isFeatured">
        <el-radio :value="1">是</el-radio>
        <el-radio :value="0">否</el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="商品状态">
      <el-radio-group v-model="productForm.status">
        <el-radio :value="1">上架</el-radio>
        <el-radio :value="0">下架</el-radio>
      </el-radio-group>
      <!-- <div class="status-tip">
        <el-alert type="info" :closable="false" show-icon>
          <p>
            提示：新增或修改商品后，状态为"待审核"(PENDING)，需要管理员审核通过后才会显示为"上架"(ON_SHELF)。
          </p>
        </el-alert>
      </div> -->
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(formRef)" :loading="loading"
        >保存</el-button
      >
      <el-button @click="cancelForm">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.product-form {
  max-width: 800px;
  margin: 0 auto;
}

.product-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.product-image-uploader:hover {
  border-color: #409eff;
}

.product-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

.status-tip {
  margin-top: 10px;
  font-size: 12px;
}
</style>
